const Response = require('../utils/response');

const responseMiddleware = (req, res, next) => {
  const originalJson = res.json;
  res.json = function(data) {
    if (data && (data.code !== undefined && data.success !== undefined)) {
      return originalJson.call(this, data);
    }
    
    const statusCode = res.statusCode;
    if (statusCode >= 200 && statusCode < 300) {
      return originalJson.call(this, Response.success(data));
    } else {
      return originalJson.call(this, Response.error(data.message || '操作失败', statusCode, data));
    }
  };
  next();
};

module.exports = responseMiddleware;